package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.customer.enums.CustomerPlanEnum;
import org.zpmis.domain.customer.enums.IntentionEnum;
import org.zpmis.domain.customer.enums.ReturnVisitEnum;
import org.zpmis.domain.customer.model.CustomerPlan;
import org.zpmis.domain.customer.model.Intention;
import org.zpmis.domain.customer.model.ReturnVisit;
import org.zpmis.domain.customer.qo.*;
import org.zpmis.domain.customer.service.CustomerPlanService;
import org.zpmis.domain.customer.service.IntentionService;
import org.zpmis.domain.customer.service.ReturnVisitService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.zpmis.domain.customer.vo.GetVisitDetailVo;
import org.zpmis.domain.customer.vo.QueryReturnVisitRecordVo;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-2
 * Time: 14:48:50
 */
@Service
@Slf4j
public class ReturnVisitWebService extends BaseWebService {
     @Reference
     private ReturnVisitService returnVisitService;

     @Reference
     private IntentionService intentionService;

     @Reference
     private CustomerPlanService customerPlanService;

     /**
      * 查询意向客户回访记录集合
      * @param queryReturnVisitRecordQo
      * @return
      */
     public PageInfo queryReturnVisitRecord(QueryReturnVisitRecordQo queryReturnVisitRecordQo) throws Exception{

          Condition condition = new Condition(ReturnVisit.class);
          Example.Criteria criteria = condition.createCriteria();
          criteria.andEqualTo("isDeleted",ReturnVisitEnum.NOT_DELETE.code());
          criteria.andEqualTo("intentionId",queryReturnVisitRecordQo.getIntentionId());
          condition.orderBy("createTime").desc();
          PageHelper.startPage(queryReturnVisitRecordQo.getPageNum(),queryReturnVisitRecordQo.getPageSize());
          List<ReturnVisit> visitList = returnVisitService.findByCondition(condition);
          PageInfo pageInfo = new PageInfo(visitList);
          //设置自定义返回对象
          List<QueryReturnVisitRecordVo> resultList = visitList.stream().map(QueryReturnVisitRecordVo::new).collect(Collectors.toList());
          pageInfo.setList(resultList);
          return pageInfo;
     }

     /**
      * 新增回访记录
      * @param addReturnVisitQo
      * @throws Exception
      */
     public void addReturnVisit(AddReturnVisitQo addReturnVisitQo) throws BusinessException,Exception{
          Integer visitObject = addReturnVisitQo.getVisitObject();
          //意向回访时  意向表id不能为空
          if(visitObject == ReturnVisitEnum.VISIT_OBJECT_INTENTION.code() && addReturnVisitQo.getIntentionId() == null){
               throw new BusinessException(ResultCode.PARAM_ERROR);
          }
          //企业回访时  企业表id不能为空
          if(visitObject == ReturnVisitEnum.VISIT_OBJECT_COMPANY.code() && addReturnVisitQo.getCompanyId() == null){
               throw new BusinessException(ResultCode.PARAM_ERROR);
          }
          //根据意向客户id 查询意向客户
          Long intentionId = addReturnVisitQo.getIntentionId();
          Intention intention = intentionService.findById(intentionId);
          if(intention == null){
               throw new BusinessException(ResultCode.DATA_NOT_FOUND);
          }
          //如果是计划来的回访 则同步修改计划的状态为已完结
          Long planId = addReturnVisitQo.getPlanId();
          if(planId != null){
               CustomerPlan customerPlan = customerPlanService.findById(planId);
               if(customerPlan != null){
                    customerPlanService.update(CustomerPlan.builder().id(planId).status(CustomerPlanEnum.ENABLE_STATUS.code()).build());
               }
          }
          //已经回访的意向客户不能重复回访
          /*if(intention.getStatus() == IntentionEnum.ENABLE_STATUS.code()){
               throw new BusinessException(ResultCode.INTENTION_RETURNVISIT_EXISTS);
          }*/
          if(intention.getStatus() != IntentionEnum.ENABLE_STATUS.code()){
               //修改意向客户状态为已回访
               intentionService.update(
                       Intention.builder()
                               .id(intention.getId())
                               .status(IntentionEnum.ENABLE_STATUS.code())
                               .build()
               );
          }

          //获取当前登录用户
          AdminLoginUser adminLoginUser = super.getAdminLoginUser();
          returnVisitService.save(
               ReturnVisit.builder()
                       .chargePerson(addReturnVisitQo.getChargePerson())
                       .chargePersonId(addReturnVisitQo.getChargePersonId())
                       .createTime(Instant.now().toEpochMilli())
                       .companyName(addReturnVisitQo.getCompanyName())
                       //意向表id 和 企业表id 二选一 根据回访对象决定
                       .intentionId(addReturnVisitQo.getIntentionId())
                       .companyId(addReturnVisitQo.getCompanyId())
                       .visitLog(addReturnVisitQo.getVisitLog())
                       .contactPerson(addReturnVisitQo.getContactPerson())
                       .contactMobile(addReturnVisitQo.getContactMobile())
                       .visitResult(addReturnVisitQo.getVisitResult())
                       .resultDesc(addReturnVisitQo.getResultDesc())
                       .followPlan(addReturnVisitQo.getFollowPlan())
                       .visitType(addReturnVisitQo.getVisitType())
                       .visitTime(addReturnVisitQo.getVisitTime())
                       .visitNextTime(addReturnVisitQo.getVisitNextTime())
                       .isDeleted(ReturnVisitEnum.NOT_DELETE.code())
                       .status(ReturnVisitEnum.DISABLE_STATUS.code())
                       .isRemind(addReturnVisitQo.getIsRemind())
                       .createId(adminLoginUser.getId())
                       .createPerson(adminLoginUser.getUserName())
                       .remake(addReturnVisitQo.getRemake())
                       .visitObject(addReturnVisitQo.getVisitObject())
                       .companyCode(intention.getCompanyCode())
                       .build());
     }

     /**
      * 修改回访记录
      * @param editReturnVisitQo
      */
     public void editReturnVisit(EditReturnVisitQo editReturnVisitQo) throws Exception{
          Long id = editReturnVisitQo.getId();
          ReturnVisit returnVisit = returnVisitService.findById(id);
          if(returnVisit == null){
               throw new BusinessException(ResultCode.DATA_NOT_FOUND);
          }
          returnVisit.setChargePersonId(editReturnVisitQo.getChargePersonId());
          returnVisit.setChargePerson(editReturnVisitQo.getChargePerson());
          returnVisit.setVisitLog(editReturnVisitQo.getVisitLog());
          returnVisit.setCompanyName(editReturnVisitQo.getCompanyName());
          returnVisit.setContactPerson(editReturnVisitQo.getContactPerson());
          returnVisit.setContactMobile(editReturnVisitQo.getContactMobile());
          returnVisit.setVisitResult(editReturnVisitQo.getVisitResult());
          returnVisit.setResultDesc(editReturnVisitQo.getResultDesc());
          returnVisit.setFollowPlan(editReturnVisitQo.getFollowPlan());
          returnVisit.setVisitType(editReturnVisitQo.getVisitType());
          returnVisit.setVisitTime(editReturnVisitQo.getVisitTime());
          returnVisit.setVisitNextTime(editReturnVisitQo.getVisitNextTime());
          returnVisit.setIsRemind(editReturnVisitQo.getIsRemind());
          returnVisit.setRemake(editReturnVisitQo.getRemake());
          returnVisitService.update(returnVisit);
     }

     public PageInfo returnVisitList(ReturnVisitListQo returnVisitListQo) throws Exception{
          Long intentionId = returnVisitListQo.getIntentionId();
          Integer visitResult = returnVisitListQo.getVisitResult();
          Integer visitType = returnVisitListQo.getVisitType();
          String chargePerson = returnVisitListQo.getChargePerson();
          Long chargePersonId = returnVisitListQo.getChargePersonId();
          String contactPerson = returnVisitListQo.getContactPerson();
          String contactMobile = returnVisitListQo.getContactMobile();
          Long startTime = returnVisitListQo.getStartTime();
          Long endTime = returnVisitListQo.getEndTime();
          String companyName = returnVisitListQo.getCompanyName();
          Condition condition = new Condition(ReturnVisit.class);
          Example.Criteria criteria = condition.createCriteria();
          criteria.andEqualTo("isDeleted",ReturnVisitEnum.NOT_DELETE.code());

          if(intentionId != null){
               criteria.andEqualTo("intentionId",intentionId);
          }
          if(visitResult != null){
               criteria.andEqualTo("visitResult",visitResult);
          }
          if(visitType != null){
               criteria.andEqualTo("visitType",visitResult);
          }
          if(StringUtil.isNotEmpty(chargePerson)){
               criteria.andLike("chargePerson", "%" + chargePerson + "%");
          }
          if(chargePersonId != null){
               criteria.andEqualTo("chargePersonId",chargePersonId);
          }
          if(StringUtil.isNotEmpty(contactPerson)){
               criteria.andLike("contactPerson", "%" + contactPerson + "%");
          }
          if(StringUtil.isNotEmpty(contactMobile)){
               criteria.andLike("contactMobile", "%" + contactMobile + "%");
          }
          if(StringUtil.isNotEmpty(companyName)){
               criteria.andLike("companyName", "%" + companyName + "%");
          }
          if(startTime != null && endTime != null){
               criteria.andGreaterThanOrEqualTo("createTime",startTime);
               criteria.andLessThanOrEqualTo("createTime",endTime);
          }
          if(startTime == null && endTime != null){
               criteria.andLessThanOrEqualTo("createTime",endTime);
          }
          if(startTime != null && endTime == null){
               criteria.andGreaterThanOrEqualTo("createTime",startTime);
               criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
          }
          condition.orderBy("createTime").desc();
          PageHelper.startPage(returnVisitListQo.getPageNum(),returnVisitListQo.getPageSize());
          List<ReturnVisit> returnVisitList = returnVisitService.findByCondition(condition);
          PageInfo pageInfo = new PageInfo<>(returnVisitList);
          //设定自定义返回对象
          List<QueryReturnVisitRecordVo> resultList = returnVisitList.stream().map(QueryReturnVisitRecordVo::new).collect(Collectors.toList());
          //根据回访表里的意向id 关联查出意向表的openId
          for(QueryReturnVisitRecordVo visitRecordVo : resultList){
               if(visitRecordVo.getIntentionId() != null){
                    Intention intention = intentionService.findById(visitRecordVo.getIntentionId());
                    visitRecordVo.setOpenId(intention.getOpenId());
               }
          }
          pageInfo.setList(resultList);
          return pageInfo;
     }

     public GetVisitDetailVo getVisitDetail(GetVisitDetailQo getVisitDetail) throws Exception{
          Long id = getVisitDetail.getId();
          ReturnVisit returnVisit = returnVisitService.findById(id);
          if(returnVisit == null){
               throw new BusinessException(ResultCode.DATA_NOT_FOUND);
          }
          GetVisitDetailVo visitDetail = GetVisitDetailVo.toVisitDetailVo(returnVisit);
          return visitDetail;
     }
}
